<script>
import border from "@/views/formShortLink/border/index.vue";
import {getGpsInfoByUserId} from "@/api/gpsinfo";

export default {
  components: { border },
  props: ['data'],
  data() {
    const today = new Date();
    const todayStr = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, '0')}-${String(today.getDate()).padStart(2, '0')}`;


    return {
      foldUPBoolean: false,
      startTime: `${todayStr} 00:00:00`,
      endTime: `${todayStr} 23:59:59`,
      tableData: [],
      loading: false,
      currentPage: 1,
      pageSize: 300000,
      total: 0
    }
  },
  mounted() {
    // 组件挂载时自动加载数据
    this.fetchTrajectoryData();
  },
  methods: {

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置到第一页
      this.fetchTrajectoryData();
    },

    // 当前页改变时触发
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTrajectoryData();
    },
    // 获取轨迹数据
    async fetchTrajectoryData() {
      this.loading = true;
      try {
        if (this.startTime && this.endTime && new Date(this.startTime) > new Date(this.endTime)) {
          this.$message.warning('开始时间不能大于结束时间');
          return;
        }

        const params = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          startTime: this.startTime,
          endTime: this.endTime,
          name:  this.data.name ||  '', // 假设data中有name属性
        };

        const response = await getGpsInfoByUserId(params)

        if (response.code === 200) {
          // 根据接口返回的数据结构进行调整
          this.tableData = response.data.records;
          this.total = response.data.total;

          // 如果接口返回的数据字段与表格字段不一致，需要转换
          // this.tableData = this.transformTableData(response.data.data.records);
        } else {
          this.$message.error('获取轨迹数据失败');
        }
      } catch (error) {
        console.error('获取轨迹数据出错:', error);
        this.$message.error('获取数据失败，请检查时间段是否正确');
      } finally {
        this.loading = false;
      }
    },

    // 格式化日期时间（如果需要特定格式）
    // 格式化日期时间（处理时间戳）
    formatDateTime(row, column, cellValue) {
      if (!cellValue) return '';
      // 如果是时间戳（秒级），需要乘以1000转换为毫秒
      const timestamp = String(cellValue).length === 10 ? cellValue * 1000 : cellValue;
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },


    // 数据转换方法（如果接口返回字段与表格字段不一致）
    transformTableData(apiData) {
      return apiData.map(item => ({
        时间: item.time || item.gpsTime,
        间隔: item.interval || '2分钟', // 根据实际情况计算或获取
        模式: item.mode || '网络',
        停留: item.stayTime || item.stay || '3',
        路距: item.distance || item.routeDistance || '35',
        速度: item.speed || '8',
        // 扩展数据，用于详情显示
        lng: item.longitude,
        lat: item.latitude,
        address: item.address || '湖北省武汉市XXXXX附近28米处'
      }));
    },
    showMap() {
      this.$emit('showMap', this.data,this.tableData)
      this.$emit('time-range-selected', this.startTime, this.endTime, this.data);
      this.$refs.borderRef.setfoldUp(true);

      // 查询时重新加载数据
      this.fetchTrajectoryData();
    },

    mapStart(v) {
      this.$emit('play', v)
      this.$refs.borderRef.setfoldUp(true)
    },

    // 前一天
    previousDay() {
      const date = new Date(this.startTime);
      date.setDate(date.getDate() - 1);
      this.startTime = this.formatDate(date) + ' 00:00:00';
      this.endTime = this.formatDate(date) + ' 23:59:00';
      this.fetchTrajectoryData();
    },

    // 后一天
    nextDay() {
      const date = new Date(this.startTime);
      date.setDate(date.getDate() + 1);
      this.startTime = this.formatDate(date) + ' 00:00:00';
      this.endTime = this.formatDate(date) + ' 23:59:00';
      this.fetchTrajectoryData();
    },

    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 导出数据
    exportData() {
      // 实现导出逻辑
      this.$message.info('导出功能开发中...');
    }
  }
}
</script>

<template>
  <border title="轨迹回放" ref="borderRef" :foldUpBtn="true" w="800px" h="600px" @close="$emit('close')"
          :foldUp="foldUPBoolean" x="630px" y="20%">
    <div class="trajectoryPage">
      <div class="top">
        <el-form :inline="true" size="mini">
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="startTime"
              style="width: 180px;"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :clearable="false"/>
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              style="width: 180px;"
              v-model="endTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              :clearable="false"/>
          </el-form-item>
          <el-form-item>
<!--            <el-button type="primary" size="mini" @click="showMap" :loading="loading">查询</el-button>-->
            <el-button type="primary" size="mini" @click="fetchTrajectoryData()" :loading="loading">查询</el-button>
            <el-button type="primary" size="mini" @click="previousDay">前一天</el-button>
            <el-button type="primary" size="mini" @click="nextDay">后一天</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="centerDiv">
        <el-table
          :data="tableData"
          size="mini"
          border
          default-expand-all
          height="100%"
          style="width: 100%;"
          v-loading="loading">
<!--          <el-table-column type="expand" width="1">-->
<!--            <template slot-scope="props">-->
<!--              {{ props.row.address || '湖北省武汉市XXXXX附近28米处' }}-->
<!--              <span style="color: #E6A23C">-->
<!--                {{ props.row.lng || '119.123456' }},{{ props.row.lat || '26.123456' }}-->
<!--              </span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column type="index" label="序号" align="center" width="55" />
          <el-table-column prop="realName" label="姓名" align="center" />
          <el-table-column prop="remark1" label="当前位置" align="center"  width="155"/>
          <el-table-column prop="time" label="时间" align="center"  width="150" :formatter="formatDateTime" />
          <el-table-column prop="lng" label="经度" align="center" />
          <el-table-column prop="lat" label="纬度" align="center" />
          <el-table-column prop="distance" label="距离(米)" align="center" />
        </el-table>


      </div>
      <div class="bottom">
        <el-button type="primary" size="mini" @click="showMap">显示轨迹</el-button>
        <el-button type="primary" size="mini" @click="mapStart('start')">播放动画</el-button>
        <el-button type="primary" size="mini" @click="mapStart('pause')">暂停播放</el-button>
        <el-button type="primary" size="mini" @click="mapStart('stop')">停止播放</el-button>
        <el-button type="primary" size="mini" @click="mapStart('clear')">清空轨迹</el-button>
<!--        <el-button type="primary" size="mini" @click="exportData">导出数据</el-button>-->
      </div>
    </div>
  </border>
</template>

<style scoped lang="scss">
.trajectoryPage {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  padding: 10px;

  ::v-deep .el-table__expand-icon--expanded {
    display: none;
  }

  .top {
    display: flex;
    flex-direction: column;
  }

  .centerDiv {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: calc(100% - 80px);
    margin-bottom: 10px;
    //background-color: #00afff;
  }
}
</style>
